package com.twan.kotlinbase.fragment

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import butterknife.OnClick
import com.blankj.utilcode.util.SPUtils
import com.google.android.material.tabs.TabLayoutMediator
import com.jaeger.library.StatusBarUtil
import com.lxj.xpopup.XPopup
import com.scwang.smart.refresh.header.ClassicsHeader
import com.twan.kotlinbase.R
import com.twan.kotlinbase.adapter.BottomViewPagerAdapter
import com.twan.kotlinbase.adapter.MyBannerImageAdapter
import com.twan.kotlinbase.app.BaseDataBindingFragment
import com.twan.kotlinbase.app.Need
import com.twan.kotlinbase.app.permissionArr
import com.twan.kotlinbase.bean.BannerBean
import com.twan.kotlinbase.bean.SpiBean
import com.twan.kotlinbase.databinding.Tab1FragmentUserBinding
import com.twan.kotlinbase.event.HotRefresh
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.pop.StatementPopup
import com.twan.kotlinbase.ui.LoginActivity
import com.twan.kotlinbase.ui.SendActivity
import com.twan.kotlinbase.ui.ServiceActivity
import com.twan.kotlinbase.util.InputUtils
import com.twan.kotlinbase.util.MyUtils
import com.twan.kotlinbase.util.RxPermissionsUtil
import com.twan.kotlinbase.util.SpiUtils
import com.twan.kotlinbase.widgets.router.Router
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.indicator.CircleIndicator
import com.zaaach.citypicker.CityPicker
import com.zaaach.citypicker.adapter.OnPickListener
import com.zaaach.citypicker.model.City
import com.zaaach.citypicker.model.HotCity
import com.zaaach.citypicker.model.LocateState
import com.zaaach.citypicker.model.LocatedCity
import kotlinx.android.synthetic.main.activity_send.*
import kotlinx.android.synthetic.main.tab1_fragment.*
import kotlinx.android.synthetic.main.tab1_fragment_user.*
import kotlinx.android.synthetic.main.tab1_fragment_user.refreshLayout
import kotlinx.android.synthetic.main.viewstub2_zhibo.*
import org.greenrobot.eventbus.EventBus
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse


class Tab1UserFragment: BaseDataBindingFragment<Tab1FragmentUserBinding>() {
    val tabs = mutableListOf("店铺直播","短视频制作","短视频推广","演员模特")
    var currpos=0
    override fun getLayoutId(): Int {
        return R.layout.tab1_fragment_user
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {
        StatusBarUtil.setColor(mActivity, resources.getColor(R.color.head_bg), 0)
        title?.visibility=View.VISIBLE
        title?.text="首页"
        back?.visibility=View.GONE
        searchView?.visibility=View.GONE//一期隐藏
        tv_back_text?.visibility=View.GONE////一期隐藏
        tv_back_text?.text="请选择"
        tv_back_text?.textSize=16f


        initBanner()

        setupViewPager()
        initTab()
        initSpi()
        initRefresh()
        showStatement()
    }

    override fun onResume() {
        super.onResume()
        edt_mobile.setText(if (MyUtils.isLogin()) MyUtils.getLoginInfo()!!.userName else "")
    }

    private fun showStatement(){
        if (SPUtils.getInstance().getBoolean("isFirstUse",true)){
            XPopup.Builder(mActivity).dismissOnTouchOutside(false).
            dismissOnBackPressed(false).asCustom(StatementPopup(mActivity){
                SPUtils.getInstance().put("isFirstUse",false)
            }).show()
        }
    }



    fun initSpi(){
        var spiData = mutableListOf<SpiBean>()
        spiData.add(SpiBean("店铺直播"))
        spiData.add(SpiBean("短视频制作"))
        spiData.add(SpiBean("短视频推广"))
        spiData.add(SpiBean("模特"))
        spiData.add(SpiBean("演员"))
        SpiUtils.setSpi(spi_select_service,spiData){ pos, bean ->
            currpos=pos
        }
    }

    @OnClick(R.id.rl_dianpu_1,R.id.rl_video_2,R.id.rl_ext_3,R.id.rl_dance_4)
    fun start(view:View){
        var need=Need.SHOP_LIVE
        when (view.id) {
            R.id.rl_dianpu_1 -> need=Need.SHOP_LIVE
            R.id.rl_video_2 -> need=Need.SHORT_VIDEO_MAKE
            R.id.rl_ext_3 -> need=Need.SHORT_VIDEO_PROMOTE
            R.id.rl_dance_4 -> need=Need.ACTOR_MODEL
        }
        Router.newIntent(mActivity).putSerializable("need", need).to(ServiceActivity::class.java).launch()
    }

    @OnClick(R.id.btn_start)
    fun recommond(){
        if (!MyUtils.isLogin()){
            Router.newIntent(mActivity).to(LoginActivity::class.java).launch()
            return
        }
        if (!InputUtils.checkEmpty(edt_mobile)) return
        //Router.newIntent(mActivity).putInt("data",1).putInt("index",currpos).to(SendActivity::class.java).launch()
        if(currpos ==0) {
            Router.newIntent(mActivity).putSerializable("need", Need.SHOP_LIVE).to(ServiceActivity::class.java).launch()
        } else if (currpos ==1){
            Router.newIntent(mActivity).putSerializable("need", Need.SHORT_VIDEO_MAKE).to(ServiceActivity::class.java).launch()
        } else if (currpos ==2){
            Router.newIntent(mActivity).putSerializable("need", Need.SHORT_VIDEO_PROMOTE).to(ServiceActivity::class.java).launch()
        } else{
            Router.newIntent(mActivity).putSerializable("need", Need.ACTOR_MODEL).to(ServiceActivity::class.java).launch()
        }
    }



    @OnClick(R.id.tv_back_text)
    fun city(){
        val hotCities: MutableList<HotCity> = ArrayList()
        hotCities.add(HotCity("北京", "北京", "101010100")) //code为城市代码
        hotCities.add(HotCity("上海", "上海", "101020100"))
        hotCities.add(HotCity("广州", "广东", "101280101"))
        hotCities.add(HotCity("深圳", "广东", "101280601"))
        hotCities.add(HotCity("杭州", "浙江", "101210101"))
        RxPermissionsUtil.requestPermission(mActivity!!,*permissionArr) {
            CityPicker.from(activity) //activity或者fragment
                .enableAnimation(true)    //启用动画效果，默认无
                .setLocatedCity(LocatedCity("杭州", "浙江", "101210101"))  //APP自身已定位的城市，传null会自动定位（默认） LocatedCity("杭州", "浙江", "101210101")
                .setHotCities(hotCities)    //指定热门城市
                .setOnPickListener(object : OnPickListener {
                    override fun onPick(position: Int, data: City) {
                        tv_back_text?.text = data.name
                    }

                    override fun onCancel() {
                        //ToastUtils.showShort("取消选择")
                    }

                    override fun onLocate() {
                        //定位接口，需要APP自身实现，这里模拟一下定位 //定位完成之后更新数据
                        CityPicker.from(this@Tab1UserFragment).locateComplete(
                                LocatedCity("深圳", "广东", "101280601"),
                                LocateState.SUCCESS
                        );
                    }
                }).show()
        }
    }

    fun initBanner() {
        RxHttpScope().launch {
            var req = RxHttp.get("/banner/findAll").toResponse<List<BannerBean>>().await()
            var adapter = MyBannerImageAdapter(mActivity!!, req)
            you_banner.let {
                it.setIndicatorGravity(IndicatorConfig.Direction.CENTER)
                it.indicator = CircleIndicator(mActivity)
                it.adapter = adapter
            }
        }
    }

    fun initRefresh(){
        refreshLayout.setRefreshHeader(ClassicsHeader(mActivity))
        refreshLayout.setOnRefreshListener { reqData() }
        refreshLayout.setEnableLoadMore(false)
        refreshLayout.setEnableRefresh(true)
    }

    override fun reqData() {
        initBanner()
        EventBus.getDefault().post(HotRefresh())
        refreshLayout.finishRefresh()
    }


    private fun setupViewPager() {
        //view_pager.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT//禁用预加载
        var fragments= mutableListOf<Fragment>()
        fragments.add(HomtHotFragment(Need.SHOP_LIVE))
        fragments.add(HomtHotFragment(Need.SHORT_VIDEO_MAKE))
        fragments.add(HomtHotFragment(Need.SHORT_VIDEO_PROMOTE))
        fragments.add(HomtHotFragment(Need.ACTOR_MODEL))
        var adapter = BottomViewPagerAdapter(mActivity as FragmentActivity,fragments)
        view_pager.adapter = adapter
    }

    fun initTab(){
        TabLayoutMediator(tablayout,view_pager) { tab, position ->
            tab.text=tabs[position]
        }.attach()
        //默认选中
        //tablayout.getTabAt(0)!!.select()
        //view_pager.currentItem = 0
    }

}